    var chapters   = null;
    var aOpen      = "Открыть";
    var aSave      = "Сохранить на SD";
    var position   = 0;
    var listSize   = 20;
    var name       = null;
    var pages      = null;
    var folderName = null;
    var unload     = null;
    var liId       = null;
    var type 	   = null;

    $(document).ready(function(){ 
        initParam();
        setStyle("type");
        
        $("#a_head_l").hide();
        $("#a_head_r").hide();
        
        $.mobile.loading('show');   
        var http = "http://anibox.me/api.php?"+getUpdateRequest();
        $.getJSON(http, parseJson);  
    });  
    
    function parseJson(data){
        name = data[0].title;
        document.getElementById("p_head").innerHTML = name;
        var append = "";
        
        var style = ' color="blue"';
        
        if ( (data[0].description != null) && (data[0].description != "")  )
            append += '<p><b><font '+style+'>ОПИСАНИЕ: </font></b>' + data[0].description + '</p>';
        
        if ( (data[0].tags != null) && (data[0].tags != "") )
            append += '<p><b><font '+style+'>ТЭГИ: </font></b>' + data[0].tags + '</p>';
       
        if ( (data[0].authors != null) && (data[0].authors != "") )
            append += '<p><b><font '+style+'>АВТОР: </font></b>' + data[0].authors + '</p>';
        
        if ( (data[0].original != null) && (data[0].original != "") )
            append += '<p><b><font '+style+'>ОРИГИНАЛ: </font></b>' + data[0].original + '</p>'
            
        if ( (data[0].translators != null) && (data[0].translators != "") )    
            append += '<p><b><font '+style+'>ПЕРЕВОДЧИКИ: </font></b>' + data[0].translators + '</p>';
        
        if ( (data[0].language != null) && (data[0].language != "") )
            append += '<p><b><font '+style+'>ЯЗЫК: </font></b>' + data[0].language + '</p>';
        
        if ( (data[0].status != null) && (data[0].status != "") )
            append += '<p><b><font '+style+'>СТАТУС: </font></b>' + data[0].status + '</p>';
        
        checkBD();
            append += 
                '<input type="button" data-theme="a" id="mark" onClick="butClick();" style="width:100%;" value="закладки"/>'+ 
                '</div>'+
                '</div>'+
                '</div>\n';
        
        $('#description').append(append);
        checkBD();
        
        chapters = data[0].chapters;
        var size = 0;        
        
        if (position == -1){
            position = chapters.length-1;
            if ( chapters.length > listSize){
                size = chapters.length - parseInt(listSize) -1;
                $("#a_head_r").show();
            } 
        }else{
            if(parseInt(position)-parseInt(listSize) < 0){
                $('#a_head_l').show();
                $("#a_head_r").hide();
                size = 0; 
            }else{
                if (position != chapters.length-1)
                    $('#a_head_l').show();
                $("#a_head_r").show();
                size = parseInt(position) - parseInt(listSize);
            }
        }
        
        window.localStorage.setItem("tyPosition", position);
        for (var i=position; i>=size; i--) {
            $('#list').append(
                '<li>' +
                '<div class="div_style_update" id="' + chapters[i].id + '" onClick="liOnClick(this.id);">'+
                     chapters[i].title +
                 '</div>'+
                '</li>\n'
            );
        }
        $('#list').listview('refresh');      
        checkWatched();
        $.mobile.loading('hide');
    }
    
    function initParam(){
    	type = getParam("task");
    	console.log(type);
    
        var befoPage = window.localStorage.getItem("befoPage");
        if ( "chapter" == befoPage){
            position = window.localStorage.getItem("tyPosition");
        }else{
            position = -1;
        }
        
        listSize = getListCount();
    }
    
    //click element in list of pages
    function liOnClick(id){
        liId = id;
        var db = getBD();
        db.transaction(saveChapterToDB, errorCB, successCB);
        
        if (document.getElementById('a_head_c').innerHTML == aOpen){
        	if (type == 'get_manga'){
        		console.log('go to chapter');
            	window.location = "chapter.html?id="+id;
            }else{
            	console.log('go to ranobe');
            	window.location = "ranobe.html?id="+id;
            }
        }else{
           var conf = confirm("начать загрузку?");
           if (conf == true){
               folderName =  document.getElementById(id).innerHTML;
               $("#popupBasic").popup('open');
               saveToSD(id); 
           }
        }
    }
    
    //save chapter to sd
    function saveToSD(id){
        var http = "http://anibox.me/api.php?task=get_chapter&id="+id;
        $.getJSON(http, function(data) {
            pages = data.files;
            console.log(pages[0]);
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
        });       
    }
    
    //save images in folder
    function fileSystemSuccess(fileSystem) {        
        folderName = 'anibox/'+folderName;
        console.log(folderName);
        var directoryEntry = fileSystem.root; // to get root path to directory
        directoryEntry.getDirectory(folderName, {create: true, exclusive: true}, onDirectorySuccess, onDirectoryFail);
        var rootdir = fileSystem.root;
        var fileTransfer = new FileTransfer();
        unload = pages.length;
        
        for (var i=0; i<pages.length; i++){
           var fp = rootdir.fullPath;            
           fp = fp+"/"+folderName+"/" + i +  ".png";
           console.log(fp);
           fileTransfer.download(pages[i],fp,  
                function(entry) {
                    //alert("download complete: " + entry.fullPath);
                   console.log(entry.fullPath);
                   unload = unload - 1;
                   if(unload == 0){
                       document.getElementById("mess").innerHTML = "Загрузка завершена";  
                       $("#popupBasic").popup('open');
                       return;
                   }
                       
                   document.getElementById("mess").innerHTML = "Осталось " + unload + " из " + pages.length;           
                   $("#popupBasic").popup('open');
                },
                function(error) {
                    //alert("download error source " + error.source);
                    //alert("download error target " + error.target);
                    //alert("upload error code" + error.code);
                    console.log("upload error code" + error.code);
                }
            );
        }
    }
    
    //image save
    function onDirectorySuccess(parent) {
        console.log(parent);
    }
     
    //error
    function onDirectoryFail(error) {
        //alert("Unable to create new directory: " + error.code);
        alert("Unable to create new directory: " + error.code);
    }
     
    //error
    function fileSystemFail(evt) {
        alert(evt.target.error.code);
    }
    
    //button for save marker
    function butClick(){
        var db = getBD();
        db.transaction(saveToDB, errorCB, successCB);
        $('#mark').hide();
    }
    
    //save chapter to db
    function saveChapterToDB(tx){
        tx.executeSql('CREATE TABLE IF NOT EXISTS chapters (_id INTEGER PRIMARY KEY, id_name)');
        tx.executeSql('INSERT INTO chapters (_id, id_name) VALUES ('+liId+','+getParam("id")+')');
        //console.log(liId+","+getParam("id"));
    }
    
    //save marker to db
    function saveToDB(tx){
        tx.executeSql('CREATE TABLE IF NOT EXISTS ' + type + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name, data)');
        tx.executeSql('INSERT INTO ' + type + ' (name, data) VALUES ("'+name+'","'+getUpdateRequest()+'")');
        //console.log("insert data in db");
    }
    
    //initial bd
    function checkWatched(){
        var db = getBD();
        db.transaction(getWatchedFromDb, errorCB);
    }
    
    //query for chapters from bd
    function getWatchedFromDb(tx){
        tx.executeSql('SELECT * FROM chapters where chapters.id_name='+getParam("id"), [], queryWatched, errorCB);
    }
    
    //check watched chapters 
    function queryWatched(tx, results){
        for (var i=0; i<results.rows.length; i++){
            var elem = document.getElementById(results.rows.item(i)._id);
            if(elem != null){
                $('#'+results.rows.item(i)._id).css('color','red');
            }
        }
    }
    
    //initial bd
    function checkBD(){
        var db = getBD();
        db.transaction(getValueFromDB, errorCB);
    }
    
    //get markers from bd
    function getValueFromDB(tx){
        tx.executeSql('SELECT * FROM ' + type, [], querySuccess, errorCB);
    }
    
    // Query the success callback
    function querySuccess(tx, results) {
        for (var i=0; i<results.rows.length; i++){
            if (results.rows.item(i).name == name){
                $('#mark').hide();
                return;
            }
        }
    }    
   
    //click next of befo in footer
    function goNext(next){
       
        if (next == true){
            if ( position == 0 )
                return;
            
            $("#a_head_l").show();
            
            var size = 0;
            if ( (parseInt(position)-parseInt(listSize)) < 0 ){
                $("#a_head_r").hide();
                return;
            }else{
                position = parseInt(position)-parseInt(listSize);
            }
            
            if(parseInt(position)-parseInt(listSize) < 0){
                $("#a_head_r").hide();
                size = 0; 
            }else{
                size = position - parseInt(listSize);
            }
        }else{
            if ( position >= chapters.length-1 )
                return;
            
            $("#a_head_r").show();
            
            var size = position;
            if ( (parseInt(position)+parseInt(listSize)) >= chapters.length-1 ){
                position = chapters.length-1;   
                $("#a_head_l").hide();
            }else{
                    position = parseInt(position)+parseInt(listSize);
            }
        }
        
        window.localStorage.setItem("tyPosition", position);
        $.mobile.loading('show');
        $('#list').empty();
        for (var i=position; i>=size; i--) {
            $('#list').append(
                '<li>' +
                '<div class="div_style_update" id="' + chapters[i].id + '" onClick="liOnClick(this.id);">'+
                     chapters[i].title +
                 '</div>'+
                '</li>\n'
            );
        }
        $('#list').listview('refresh');
        $.mobile.loading('hide');
        checkWatched();
        window.scrollTo(0, 0);
    }
    
    //change in header save or open chapter
    function aClick(){
        if (document.getElementById('a_head_c').innerHTML == aSave){
            document.getElementById('a_head_c').innerHTML = aOpen;
        }else{
            document.getElementById('a_head_c').innerHTML = aSave;
        }
    }
    